package com.zeroinverse.fortunecookie;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class FortuneMessageDatabaseAdapter {
	private static final String messageFileName = "messages.txt";
	private static final String logTag = "FORTUNE_COOKIE";
	private static String databaseName = "fortune_cookie.db";
	private static final String messageTableName = "message";
	private static final String messageTableKeyId = "_id";
	private static final String messageTableKeyContent = "content";
	private static final String messageTableKeyPulled = "pulled";
	private static final String messageTableKeyUnixtime = "unixtime";
	private static final String messageTableKeyHumantime ="humantime";
	
	private static final String databaseCreate =
		"CREATE TABLE " + messageTableName + "(" + 
		"_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " + 
		"content TEXT NOT NULL, " +
		"pulled INTEGER NOT NULL DEFAULT 0, " +
		"unixtime TIMESTAMP, " +
		"humantime TEXT)";
	
	private static final int databaseVersion = 9;
	//private static String databaseFullPath;
	
	private Context context;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;
	
	public String getMessageTableKeyId() {
		return messageTableKeyId;
	}
	public String getMessageTableKeyContent() {
		return messageTableKeyContent;
	}
	public String getMessageTableKeyPulled() {
		return messageTableKeyPulled;
	}
	public String getMessageTableKeyUnixtime() {
		return messageTableKeyUnixtime;
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper {
		
		private AssetManager am;
		
		public DatabaseHelper(Context context) {
			super(context, databaseName, null, databaseVersion);
			am = context.getResources().getAssets();
		}
		
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			Log.i(logTag, "Database creation...");
			db.execSQL(databaseCreate);
			
			try {
				InputStream is = am.open(messageFileName);
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String line;
				while ((line = br.readLine()) != null) {
					Log.i(logTag, line);
					db.execSQL("INSERT INTO " + messageTableName + " (" + messageTableKeyContent + ") " + "VALUES ('" + line + "')");
				}
			} catch (Exception e) {
				
			}
		}

		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			Log.i(logTag, "Database upgrade: " + oldVersion + " to " + newVersion + "...");
			db.execSQL("DROP TABLE IF EXISTS " + messageTableName);
			onCreate(db);
		}
	}
    
	public FortuneMessageDatabaseAdapter(Context context) {
		this.context = context;
	}
	
	public FortuneMessageDatabaseAdapter open() throws SQLException {
		dbHelper = new DatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close() {
		dbHelper.close();
	}
	
	/* Handle message table */
	public long createMessage(String content) {
		ContentValues values = new ContentValues();
		values.put(messageTableKeyContent, content);
		return db.insert(messageTableName, null, values);
	}
	
	public boolean deleteMessage(long rowID) {
		return db.delete(messageTableName, messageTableKeyId + "=" + rowID, null) > 0;
	}
	
	public Cursor fetchAllMessages() {
		return db.query(
				messageTableName, 
				new String[] {
					messageTableKeyId,
					messageTableKeyContent,
					messageTableKeyPulled,
					messageTableKeyUnixtime},
				null,
				null,
				null,
				null,
				null);
	}
	
	public Cursor fetchMessage(boolean pulled) {
		String pulled_string;
		if (pulled == false) {
			pulled_string = "0";
		} else {
			pulled_string = "1";
		}
		Cursor cursor = db.query(
				true,
				messageTableName,
				new String[] {
					messageTableKeyId,
					messageTableKeyContent,
					messageTableKeyPulled,
					messageTableKeyUnixtime},
				messageTableKeyPulled + "=" + pulled_string,
				null,
				null,
				null,
				messageTableKeyUnixtime + " desc",
				null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		return cursor;
	}
	
	public Cursor fetchMessage(long rowID) throws SQLException {
		Cursor cursor = db.query(
				true,
				messageTableName,
				new String[] {
					messageTableKeyId,
					messageTableKeyContent,
					messageTableKeyPulled,
					messageTableKeyUnixtime},
				messageTableKeyId + "=" + rowID,
				null,
				null,
				null,
				null,
				null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		return cursor;
	}
	
	
	public boolean updateMessage(long rowID, String content) {
		ContentValues value = new ContentValues();
		value.put(messageTableKeyContent, content);
		return db.update(messageTableName, value, messageTableKeyId + "=" + rowID, null) > 0;
	}
	
	public boolean updateMessage(long rowID, boolean pulled, Long timestamp) {
		ContentValues value = new ContentValues();
		if (pulled == false) {
			value.put(messageTableKeyPulled, 0);
		} else {
			value.put(messageTableKeyPulled, 1);
		}
		value.put(messageTableKeyUnixtime, timestamp);
		return db.update(messageTableName, value, messageTableKeyId + "=" + rowID, null) > 0;
	}
	
	public boolean updateMessage(long rowID, Long timestamp) {
		ContentValues value = new ContentValues();
		value.put(messageTableKeyUnixtime, timestamp);
		return db.update(messageTableName, value, messageTableKeyId + "=" + rowID, null) > 0;
	}
}
